<template>
  <div>

    <div class="card" style="margin-bottom: 5px;">
      <el-button type="primary" @click="load">刷新</el-button>
      <el-button type="success" @click="handleAdd">新增</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" stripe>
        <el-table-column label="标题" prop="title"></el-table-column>
        <el-table-column label="封面">
          <template #default="scope">
            <el-image :src="scope.row.cover" style="width: 40px; height: 40px; border-radius: 50%"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="类型" prop="type"></el-table-column>
        <el-table-column label="口味" prop="taste"></el-table-column>
        <el-table-column label="图片集">
          <template #default="scope">
            <el-image style="width: 50px; height: 50px; border-radius: 5px" :src="scope.row.imgs[0]"
                      :preview-src-list="scope.row.imgs" preview-teleported></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" width="160">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" v-model:page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total"/>
    </div>

    <el-dialog title="信息" width="40%" v-model="data.formVisible" :close-on-click-modal="false" destroy-on-close>
      <el-form :rules="data.rules" :model="data.form" label-width="100px" style="padding-right: 50px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="data.form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-upload :limit="1" :action="uploadUrl" list-type="picture" :on-success="handleImgSuccess">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="data.form.type"
            class="m-2"
            placeholder="选择类型"
            size="large"
            style="width: 400px"
          >
            <el-option
              v-for="item in data.types"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="食物内容" prop="content">
          <!-- <el-input type="textarea" v-model="data.form.content" autocomplete="off" /> -->
          <el-select
            v-model="data.form.content"
            multiple
            size="large"
            placeholder="请选择食物"
            style="width: 400px"
          >
            <el-option
              v-for="item in data.foods"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="口味" prop="taste">
          <el-select
            v-model="data.form.taste"
            class="m-2"
            placeholder="选择口味"
            size="large"
            style="width: 400px"
          >
            <el-option
              v-for="item in data.tastes"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="taste">
          <el-input type="textarea" v-model="data.form.description" autocomplete="off" />
        </el-form-item>
        <el-form-item label="图片集" prop="imgs">
          <el-upload :on-remove="handleRemove" :action="uploadUrl" :limit="3" list-type="picture" :on-success="handleImgSuccess2">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频" prop="video">
          <el-upload :on-remove="handleRemove" :action="uploadUrl" :limit="1" list-type="picture" :on-success="handleImgSuccess3">
            <el-button type="primary">上传视频</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import request from "@/utils/request";
import {reactive} from "vue";
import {ElMessageBox, ElMessage} from "element-plus";

// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/upload'

const data = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {
    imgs: [],
    video: ''
  },
  tableData: [],
  tastes: ['重口味', '清淡', '甜食爱好者', '酸味偏好者', '辣味爱好者'],
  types: ['早餐', '午餐', '晚餐', '加餐'],
  foods: [],
  rules: {
    title: [
      { required: true, message: '不能为空', trigger: 'blur' },
    ],
    cover: [
      { required: true, message: '不能为空', trigger: 'blur' },
    ],
    type: [
      { required: true, message: '不能为空', trigger: 'blur' },
    ],
    content: [
      { required: true, message: '不能为空', trigger: 'blur' },
    ],
    taste: [
      { required: true, message: '不能为空', trigger: 'blur' },
    ],
    imgs: [
      { required: true, message: '不能为空', trigger: 'blur' },
    ],
  }
})

// 分页查询
const load = () => {
  request.get(`/food/page`, {
    params: {
      page: 1,
      pageSize: 1000,
    }
  }).then(res => {
    data.foods = res.data
  })
  request.get(`/book/page`, {
    params: {
      page: data.pageNum,
      pageSize: data.pageSize,
    }
  }).then(res => {
    data.tableData = res.data.map(v => {
      return {
        ...v,
        imgs: v.imgs ? JSON.parse(v.imgs) : []
      }
    })
    console.log(data.tableData)
    data.total = res.total
  })
}

// 新增
const handleAdd = () => {
  data.form = {
    imgs: [],
    video: ''
  }
  data.formVisible = true
}

// 编辑
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.form.content = JSON.parse(data.form.content).map(v => v.id)
  data.formVisible = true
}

// 新增保存
const add = () => {
data.form.content = JSON.stringify(data.foods.filter(v1 => data.form.content.includes(v1.id)).map(v => {
  return {
    name: v.name,
    cover: v.cover,
    id: v.id
  }
}))
  request.post('/book/add', {
    ...data.form,
    imgs: JSON.stringify(data.form.imgs)
  }).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('操作成功')
      data.formVisible = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 编辑保存
const update = () => {
  console.log(data.form)
  data.form.content = JSON.stringify(data.foods.filter(v1 => data.form.content.includes(v1.id)).map(v => {
    return {
      name: v.name,
      cover: v.cover,
      id: v.id
    }
  }))
  request.put('/book/update', {
    ...data.form,
    imgs: JSON.stringify(data.form.imgs)
  }).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('操作成功')
      data.formVisible = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 弹窗保存
const save = () => {
  // data.form有id就是更新，没有就是新增
  data.form.id ? update() : add()
}

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗?', '删除确认', { type: 'warning' }).then(res => {
    request.delete('/book/delete/' + id).then(res => {
      if (res.code === '200') {
        load()
        ElMessage.success('操作成功')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {})
}


// 处理文件上传的钩子
const handleImgSuccess = (res) => {
  data.form.cover = res.url
}
// 处理文件上传的钩子
const handleImgSuccess2 = (res) => {
  data.form.imgs.push(res.url)
}
// 处理文件上传的钩子
const handleImgSuccess3 = (res) => {
  data.form.video = res.url
}


const handleRemove = (file, uploadFiles) => {
  let index = data.form.imgs.findIndex(v => v == file.response.url)
  data.form.imgs.splice(index, 1)
}


load()
</script>